<template>
  <Dialog
    :title="dialogTitle"
    v-loading="loading"
    v-model="dialogVisible"
  >
    <div v-if="!chartData.length" style="height: 500px;">暂无数据</div>
    <div v-show="0 < chartData.length" ref="chartRef" class="chart-ref">
    </div>
  </Dialog>
</template>

<script setup lang="ts">
import * as echarts from 'echarts';

const props = defineProps<{ getData: () => Promise<any[]>; }>();

const dialogVisible = ref(false);
const dialogTitle = ref('贷款客户数量排行');
const loading = ref(false);

const chartRef = ref();
const chartData = ref([]);

function open(title) {
  dialogVisible.value = true;
  dialogTitle.value = title;

  loading.value = true;
  props
  .getData()
  .then(data => {
    chartData.value = data.list.sort((a, b) => {
      const diff = a.money - b.money;
      if (0 < diff) {
        return 1;
      } else if (diff < 0) {
        return -1;
      } else {
        return 0;
      }
    });
  })
  .then(initChart)
  .finally(() => {
    loading.value = false;
  });
}

let chart: Nullable<echarts.ECharts> = null;
function initChart() {
  chart = echarts.init(chartRef.value);
  chart.setOption({
    tooltip: {
      trigger: 'item',
      confine: true,
      extraCssText: 'max-height: 80px; overflow-y: auto;'
    },
    xAxis: {
      type: 'value',
    },
    yAxis: {
      type: 'category',
      data: chartData.value.map(item => item.userName),
    },
    series: [
      {
        name: '放款金额',
        type: 'bar',
        color: '#953735',
        barMaxWidth: 50,
        data: chartData.value.map(item => item.money),
      }
    ],
  });
}

defineExpose({ open });
</script>

<style scoped>
.chart-ref { height: 500px; }
:deep(.chart-ref > div) { height: 100%; }
</style>
